package com.bill.common.business.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.bill.common.business.dao.IBuyDAO;
import com.bill.common.business.dao.ISellDAO;
import com.bill.common.business.dto.BuyDTO;
import com.bill.common.business.dto.BuyGridDTO;
import com.bill.common.business.dto.BuyQueryDTO;
import com.bill.common.business.dto.SellGridDTO;
import com.bill.common.business.dto.SellQueryDTO;
import com.bill.common.business.entity.Buy;
import com.bill.common.system.entity.TransactionRecord;
import com.bill.common.system.service.ITransactionRecordService;
import com.bill.common.user.dao.IRegisterUserDAO;
import com.bill.common.user.entity.RegisterUser;
import com.bill.common.utils.DateUtils;
import com.bill.common.utils.DoubleFormat;
import com.bill.common.utils.ToolUtils;
import com.bill.common.utils.TranType;
import com.sinba.common.dto.PageDTO;

public class BuyService implements IBuyService {
	@Autowired
	private IBuyDAO buyDAO;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private ISellDAO sellDAO;
	@Autowired
	private ISellService sellService;
	
	
	@Transactional
	public synchronized String save(BuyDTO dto) {
		// TODO Auto-generated method stub
		//股票写法
		Double balance = transactionRecordService.findUserBalance(dto.getBuyUser(), TranType.STATIC);
		if(balance>0){
			
			Buy entity = new Buy();
			BuyDTO.dto2entity(dto, entity);
			entity.setdBuyMoney(balance);
			entity.setdSurplusMoney(balance);
			RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", dto.getBuyUser());
			entity.setUser(registerUser);
			buyDAO.merge(entity);
			entity.setBcode(ToolUtils.d6Format(entity.getId()));
			
			TransactionRecord tr1 = new TransactionRecord();
			tr1.setLoginName(dto.getBuyUser());
			tr1.setTransactionObject("system");
			tr1.setTransactionType(TranType.MaiRu);
			tr1.setRemark("买入");
			transactionRecordService.updateTran(tr1, TranType.STATIC, balance, TranType.CUT);
		}else{
			return "余额不足!";
		}
		
		return "买入成功!";
		
		
		//援助规则写法
		/*if(dto!=null && dto.getBuyUser()!=null && dto.getBuyMoney()>0){
				
				//一天只允许挂单一次
				if(oneDayOnlyAllowedBuyOne(dto.getBuyUser())){
					return "Failure to apply for assistance, day only allowed to apply once! <br> 提供援助申请失败,一天只允许申请一次!";
				}
			
				//挂出封顶5W
				Long credit = allowBuyCredit(dto.getBuyUser());
				//System.out.println("额度："+credit);
				if(credit<dto.getBuyMoney()){
					return "All aid cap 50000, also apply: "+credit+" <br> 全部援助封顶5万，还可申请："+credit;
				}
			
			
				//全部的援助申请拿足7天的日分红才允许挂单
				if(!sellService.isGetFullRiFengHong(dto.getBuyUser())){
					return "全部的提供援助申请拿满7天的日利息后才允许继续提供援助申请!";
				}else{
					//拿足7天利息+24小时后才允许提供援助申请
					//拿到最后一条提供援助申请
					BuyQueryDTO queryDTO = new BuyQueryDTO();
					queryDTO.setBuyUser(dto.getBuyUser());
					queryDTO.setLimit(1);
					PageDTO pagedto = findBuyPage(queryDTO, "desc", "id");
					if(pagedto.getTotalSize()>0){
						BuyGridDTO buyGridDto = (BuyGridDTO)pagedto.getData().get(0);
						//只要状态不是取消的都要计算8*24小时后
						if(!buyGridDto.getStatus().equals(3)){
							Calendar cl = new GregorianCalendar();
							cl.setTime(buyGridDto.getCreateTime());
							cl.set( Calendar.DATE, cl.get( Calendar.DATE )+8);
							if(new Date().getTime()<cl.getTime().getTime()){
								SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
								return "提示:截止"+format.format(cl.getTime())+"后才能再次提供援助申请!";
							}
						}
					}
				}
				
				
				
				
				*//**
				 * 1、援助未结束不允许援助申请
				 * 2、被援助未结束不允许援助申请
				 *//*
				String result = isAllowBuy(dto.getBuyUser());
				if(!"success".equals(result)){
					return result;
				}
			
				Buy entity = new Buy();
				BuyDTO.dto2entity(dto, entity);
				entity.setSurplusMoney(dto.getBuyMoney());
				
				//判断是否可能是首单
				RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", dto.getBuyUser());
				//72小时不操作冻结
				registerUser.setTempTime(registerUser.getLastOptTime());
				registerUser.setLastOptTime(null);
				registerUserDAO.merge(registerUser);
				if(registerUser.getRegisterMoney()==0){
					entity.setMayFirstSingle(true);
				}
				entity.setUser(registerUser);
				buyDAO.merge(entity);
				//将买入金额给到静态钱包
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(dto.getBuyUser());
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.MaiRu);
				tr1.setRemark("援助申请");
				transactionRecordService.updateTran(tr1, TranType.DYNAMIC, dto.getBuyMoney().doubleValue(), TranType.ADD);
				return "提供援助申请成功!";
		}else{
			return "提供援助申请失败,请重试或联系客服!";
		}
		*/
	}
	
	@Transactional
	private String isAllowBuy(String loginName){
		BuyQueryDTO queryDTO = new BuyQueryDTO();
		queryDTO.setBuyUser(loginName);
		queryDTO.setLimit(1);
		queryDTO.setMultipleStatus(new Integer[]{0,1});
		PageDTO pageDTO = findBuyPage(queryDTO,null,null);
		if(pageDTO.getTotalSize()>0){
			return "提供援助申请失败,还有援助未结束不允许援助申请!";
		}
		
		SellQueryDTO sellQueryDTO = new SellQueryDTO();
		sellQueryDTO.setSellUser(loginName);
		sellQueryDTO.setLimit(1);
		sellQueryDTO.setMultipleStatus(new Integer[]{0,1});
		PageDTO pageDTO1 = sellDAO.findSellPage(sellQueryDTO, null, null);
		if(pageDTO1.getTotalSize()>0){
			return "提供援助申请失败,得到援助未结束不允许援助申请!";
		}
		return "success";
		
	}
	
	/**
	 * 一天只允许申请一次
	 * @param buyUser
	 * @return
	 */
	private boolean oneDayOnlyAllowedBuyOne(String buyUser){
		BuyQueryDTO queryDto = new BuyQueryDTO();
		queryDto.setBuyUser(buyUser);
		queryDto.setMultipleStatus(new Integer[]{0,1,2});
		queryDto.setSearchType("todaySearch");
		PageDTO pageDto = buyDAO.findBuyPage(queryDto, null, null);
		if(pageDto!=null && pageDto.getTotalSize()>0){
			return true;
		}else{
			return false;
		}
	}
	
	
	/**
	 * 申请封顶5万，允许额度
	 * @param buyUser
	 * @return
	 */
	private Long allowBuyCredit(String buyUser){
		
		BuyQueryDTO queryDto = new BuyQueryDTO();
		queryDto.setBuyUser(buyUser);
		queryDto.setMultipleStatus(new Integer[]{0,1});
		queryDto.setLimit(50);
		PageDTO pageDto = buyDAO.findBuyPage(queryDto, null, null);
		Long total = 0L;
		if(pageDto!=null && pageDto.getTotalSize()>0){
			List<Buy> lists = (List<Buy>)pageDto.getData();
			for(Buy buy : lists){
				total = total+buy.getBuyMoney();
			}
		}
		return 50000-total;
	} 
	
	
	
	@Transactional
	public synchronized String clean(BuyDTO dto) {
		// TODO Auto-generated method stub
		Buy entity = buyDAO.findById(dto.getId());
		if(entity!=null && entity.getStatus().equals(0)){
			if(cleanTwoIn1Month(entity.getBuyUser())){
				return "取消失败，一个月只允许取消两次！";
			}else{
				//扣除静态
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(entity.getBuyUser());
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.MaiRuClean);
				tr1.setRemark("提供援助取消");
				transactionRecordService.updateTran(tr1, TranType.DYNAMIC, entity.getBuyMoney().doubleValue(), TranType.CUT);
				
				//扣除日分红
				Double rfhMoney = transactionRecordService.statStatic(entity.getBuyUser(), "日利息("+entity.getId()+")");
				if(rfhMoney!=null && rfhMoney>0){
					TransactionRecord tr2 = new TransactionRecord();
					tr2.setLoginName(entity.getBuyUser());
					tr2.setTransactionObject("system");
					tr2.setTransactionType(TranType.MaiRuClean);
					tr2.setRemark("提供援助取消(分红)");
					transactionRecordService.updateTran(tr2, TranType.DYNAMIC, rfhMoney, TranType.CUT);
				}
				entity.setStatus(3);
				buyDAO.merge(entity);
				
				RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", entity.getBuyUser());
				registerUser.setLastOptTime(registerUser.getTempTime());
				registerUserDAO.merge(registerUser);
				
				
				return "提供援助取消成功!";
			}
		}else{
			return "提供援助取消失败!";
		}
		
	}

	
	/**
	 * 一个月只允许取消两次
	 * @param buyUser
	 * @return
	 */
	private boolean cleanTwoIn1Month(String buyUser){
		BuyQueryDTO queryDto = new BuyQueryDTO();
		queryDto.setBuyUser(buyUser);
		queryDto.setStatus(3);
		queryDto.setStartTime(DateUtils.getFirstDayInMonth());
		queryDto.setEndTime(DateUtils.getLastDayInMonth());
		PageDTO pageDto = buyDAO.findBuyPage(queryDto, null, null);
		if(pageDto.getTotalSize()>=2){
			return true;
		}else{
			return false;
		}
	}
	
	@Transactional
	public PageDTO findBuyPage(BuyQueryDTO queryDto,String sord,String sidx) {
		// TODO Auto-generated method stub
		PageDTO pageDto = buyDAO.findBuyPage(queryDto, sord, sidx);
		List<Buy> lists = pageDto.getData();
		List<BuyGridDTO> dtos = new ArrayList<BuyGridDTO>();
		for(Buy buy:lists){
			BuyGridDTO dto = new BuyGridDTO();
			BuyGridDTO.entity2dto(buy, dto);
			try {
				dto.setQueuingDays(DateUtils.daysBetween(buy.getCreateTime(), new Date()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if("BuyAndSell".equals(queryDto.getSearchType())){
				//对应的卖出
				SellQueryDTO sellQueryDTO = new SellQueryDTO();
				sellQueryDTO.setBuyId(buy.getId());
				PageDTO pageDto1 = sellService.findSellPage(sellQueryDTO, "asc", "id");
				dto.setSellGrids(pageDto1.getData());
				
				//计算持有股数和买入价格
				Long holdStock = 0L;
				Set<Double> buyPrices = new HashSet<Double>();
				List<SellGridDTO> sellGridDTOs = pageDto1.getData();
				for(SellGridDTO sellGridDTO : sellGridDTOs){
					holdStock = holdStock+sellGridDTO.getSellMoney();
					buyPrices.add(sellGridDTO.getBuyPrice());
				}
				dto.setHoldStock(holdStock);
				dto.setBuyPrices(buyPrices);
			}
			
			dtos.add(dto);
		}
		pageDto.setData(dtos);
		return pageDto;
	}
	
	@Transactional
	public boolean isNotCompleteOrder(String buyUser){
		Integer[] status = {0,1};
		List<Buy> list = buyDAO.findBuy(buyUser, status);
		if(list.size()>0){
			return true;
		}else{
			return false;
		}
	};
	
	
	@Transactional
	public void changeOrder(BuyDTO buyDto){
		Buy entity = buyDAO.findById(buyDto.getId());
		if("edit".equals(buyDto.getRemark())){
			entity.setBuyPrice(buyDto.getBuyPrice());
			entity.setBuyMoney(buyDto.getBuyMoney());
			entity.setSurplusMoney(buyDto.getBuyMoney());
		}else{
			entity.setPriority(buyDto.getPriority());
			entity.setCreateTime(buyDto.getCreateDate());
		}
		buyDAO.merge(entity);
	}
	
	/**
	 * 未完成的所有买入
	 * @return
	 */
	@Transactional
	public Double undoneAllBuy(){
		Double result = 0D;
		try {
			List<Object> objs = buyDAO.undoneAllBuy();
			
			for(Object obj : objs){
				result = (Double)obj;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return DoubleFormat.format(result);
		
	}
	
}
